package com.itheima.demo1.transaction.service;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;

import com.itheima.demo1.transaction.dao.AccountDao;
import com.itheima.utils.JDBCUtils;
import com.itheima.utils.JDBCUtils2;

public class AccountService {
	
	/**
	 * 使用DBUtils进行事务管理
	 * @param from
	 * @param to
	 * @param money
	 */
	public void transfer(String from, String to, Double money) {
		AccountDao accountDao = new AccountDao();
		Connection conn = JDBCUtils.getConnection();
		try {
			conn.setAutoCommit(false);
			accountDao.outMoney(conn, from, money);
			int a = 1 / 0;
			accountDao.inMoney(conn, to, money);
			DbUtils.commitAndCloseQuietly(conn);
		} catch (Exception e) {
			DbUtils.rollbackAndCloseQuietly(conn);
			e.printStackTrace();
		}
	}
	
	/**
	 * 事务管理的第二张方法:绑定到当前线程
	 * @param from
	 * @param to
	 * @param money
	 */
	public void transfer2(String from, String to, Double money) {
		AccountDao accountDao = new AccountDao();
		
		try {
			JDBCUtils2.beginTransaction();
			accountDao.outMoney(from, money);
			int a = 1 / 0;
			accountDao.inMoney(to, money);
			JDBCUtils2.commitTransaction();
		} catch (Exception e) {
			try {
				JDBCUtils2.rollBackTransaction();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

	/**
	 * 事务管理的第一种方法:向下传递Connection
	 * 业务层转账的方法
	 * @param from
	 * @param to
	 * @param money
	 */
	public void transfer1(String from, String to, Double money) {
		AccountDao accountDao = new AccountDao();
		
		// 方式一: 在业务层获得Connection,传递给DAO
		Connection conn = null;
		try {
			conn = JDBCUtils.getConnection();
			conn.setAutoCommit(false);
//			accountDao.outMoney(conn, from, money);
			//int a = 1 / 0;
//			accountDao.inMoney(conn, to, money);
			conn.commit();
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

}
